﻿Imports Microsoft.VisualBasic

Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Net
Imports System.Text
Imports System.IO
Imports System.Security.Cryptography.X509Certificates
Imports System.Net.Security
Imports System.Collections.Specialized
Imports Newtonsoft.Json
Imports Parse.ParseGeoPoint

Public Class taxist2
    Inherits taxist

    Public Overrides Property torders As ICollection(Of torders)
        Get
            Return Nothing
        End Get
        Set(value As ICollection(Of torders))



        End Set
    End Property

End Class

Public Class Drivers

    Public city_id As Guid
    Public taxi_carnumber As String
    Public taxi_id As Guid
    Public taxi_lastname As String
    Public taxi_location As String
    Public taxi_marka As String
    Public taxi_model As String
    Public taxi_photo As String
    Public taxt_firstname As String
    Public rating As Integer
    Public taxi_color As String
    Public price As Integer = 0

    Public taxi_rating As Integer
    Public taxi_rating_count As Integer

End Class


<MetadataType(GetType(taxistMetaData))>
Partial Class taxist
End Class

Public Class taxistMetaData
    <JsonIgnore>
    Public Property Torders As ICollection(Of torders)
End Class

Namespace ASP


    Public Module WRAD_Login

        'Private _context As TaxiEntities
        '<ASP.HideData>
        'Function GetContext() As TaxiEntities

        '    'If IsNothing(HttpContext.Current.Application("_context")) = True Then

        '    '    HttpContext.Current.Application("_context") = New TaxiEntities

        '    'End If
        '    '_context = HttpContext.Current.Application("_context")

        '    _context = New TaxiEntities

        '    Return _context

        'End Function
        Private Function ConstructResponse(code As Integer, message As String, data As Dictionary(Of String, Object)) As Dictionary(Of String, Object)

            Dim result As New Dictionary(Of String, Object)

            Dim meta As New Dictionary(Of String, Object)

            meta.Add("code", code)
            meta.Add("message", message)
            result.Add("meta", meta)
            result.Add("data", data)

            Return result

        End Function

        <FunctionState(FunctionState.FState.Stable), PostParametrData({"firstname", "lastname", "phone", "password", "cityId", _
                "marka", "model", "autoNumber", "color", "photo"}, {GetType(String), GetType(String), GetType(String), GetType(String), GetType(Guid), _
                GetType(String), GetType(String), GetType(String), GetType(String), GetType(String)}), Description("Using this function, your can register your taxi driver. Remember: phone is the unique value")>
        Public Function WRAD_Register() As Dictionary(Of String, Object)

            Dim result As New Dictionary(Of String, Object)

            Dim firstname As String = HttpContext.Current.Request("firstname")
            Dim lastname As String = HttpContext.Current.Request("lastname")
            Dim phone As String = HttpContext.Current.Request("phone")
            Dim password As String = HttpContext.Current.Request("password")
            Dim cityId As String = HttpContext.Current.Request("cityId")
            Dim marka As String = HttpContext.Current.Request("marka")
            Dim model As String = HttpContext.Current.Request("model")
            Dim autoNumber As String = HttpContext.Current.Request("autoNumber")
            Dim color As String = HttpContext.Current.Request("color")

            Dim user As New taxist

            user.city_id = Guid.Parse(cityId)
            user.taxi_carnumber = autoNumber
            user.taxi_created = Now
            user.taxi_id = Guid.NewGuid
            user.taxi_lastaction = Now
            user.taxi_isacepted = False
            user.taxi_isonline = True
            user.taxi_lastname = lastname
            user.taxi_location = ""
            user.taxi_marka = marka
            user.taxi_model = model
            user.taxi_password = password
            user.taxi_phone = phone
            user.taxi_phoneconfirm = False
            user.taxi_color = color
            user.taxt_firstname = firstname

            Using context As New TaxiEntities()
                If context.taxist.Count(Function(x) x.taxi_phone = user.taxi_phone) > 0 Then
                    Return ConstructResponse(500, "NOT_UNIQUE_PHONE", result)
                End If

                If HttpContext.Current.Request.Files.Count <> 0 Then

                    Dim sh As String
                    sh = Now.Millisecond & Now.Second & Now.Month & Now.Minute & Now.Hour & Now.Year
                    sh += Mid(HttpContext.Current.Request.Files(0).FileName, InStrRev(HttpContext.Current.Request.Files(0).FileName, "."))

                    Dim filename As String = sh

                    HttpContext.Current.Request.Files(0).SaveAs(HttpContext.Current.Server.MapPath("/Images/" & filename))
                    user.taxi_photo = filename
                Else
                    user.taxi_photo = ""
                    Return ConstructResponse(500, "NEED_PHOTO", result)
                End If

                Try
                    Dim r As New Random
                    user.last_code = r.Next(1000, 9999)

                    Dim session As New WSession(HttpContext.Current)
                    If session.Data.ContainsKey("last_sms") = True Then
                        Dim dt As DateTime = CType(session.Data("last_sms"), Date)
                        If dt.AddMinutes(30) > Now Then
                            Return ConstructResponse(500, "SMS_TIMEOUT", Nothing)
                        End If
                    End If

                    Dim smsresult As String = SendSms(user.taxi_phone, "Код подтверждения: " & user.last_code)
                    session.Push("last_sms", CType(Now, String))
                    If (smsresult = "OK") Then

                        user.last_reser = Now
                        context.taxist.Add(user)

                        session.Push("WRAD_AUTH", CType(True, String))
                        session.Push("taxi_id", user.taxi_id.ToString)
                        session.Push("taxi_phone", user.taxi_phone)

                        session.SaveChanes()
                        context.SaveChanges()

                        Dim tr As New transfers
                        tr.client_id = user.taxi_id
                        tr.transfer_amount = 200
                        tr.transfer_date = Now
                        tr.transfer_code = "Регистрация +200 тг"
                        tr.transfer_id = Guid.NewGuid
                        tr.transfer_sdate = Now.ToString
                        context.transfers.Add(tr)
                        context.SaveChanges()

                        result.Add("taxist_id", user.taxi_id)
                    Else
                        Return ConstructResponse(500, "CAN'T SEND SMS: " & smsresult, result)
                    End If

                Catch ex As Exception
                    Return ConstructResponse(500, ex.Message & " " & ex.InnerException.Message, result)
                End Try
            End Using

            Return ConstructResponse(200, "USER_CREATED", result)

        End Function
        <FunctionState(FunctionState.FState.Stable), PostParametrData({"firstname", "lastname", "phone", "password", "cityId", _
            "marka", "model", "autoNumber", "color", "photo"}, {GetType(String), GetType(String), GetType(String), GetType(String), GetType(Guid), _
            GetType(String), GetType(String), GetType(String), GetType(String), GetType(String)}), Description("Using this function, your can register your taxi driver. Remember: phone is the unique value"), NeedAuth>
        Public Function WRAD_UpdateProfile() As Dictionary(Of String, Object)

            Dim firstname As String = HttpContext.Current.Request("firstname")
            Dim lastname As String = HttpContext.Current.Request("lastname")
            Dim phone As String = HttpContext.Current.Request("phone")
            Dim password As String = HttpContext.Current.Request("password")
            Dim cityId As String = HttpContext.Current.Request("cityId")
            Dim marka As String = HttpContext.Current.Request("marka")
            Dim model As String = HttpContext.Current.Request("model")
            Dim autoNumber As String = HttpContext.Current.Request("autoNumber")
            Dim color As String = HttpContext.Current.Request("color")
            Dim session As New WSession(HttpContext.Current)

            Using context As New TaxiEntities()
                Dim gui As Guid = Guid.Parse(session.Data("taxi_id"))
                Dim user As taxist = context.taxist.FirstOrDefault(Function(x) x.taxi_id = gui)

                user.city_id = Guid.Parse(cityId)
                user.taxi_carnumber = autoNumber
                user.taxi_created = Now
                user.taxi_lastaction = Now
                user.taxi_isacepted = True
                user.taxi_isonline = True
                user.taxi_lastname = lastname
                user.taxi_location = ""
                user.taxi_marka = marka
                user.taxi_model = model
                user.taxi_password = password
                user.taxi_phone = phone
                user.taxi_phoneconfirm = True
                user.taxi_color = color
                user.taxt_firstname = firstname

                If HttpContext.Current.Request.Files.Count <> 0 Then
                    Dim sh As String
                    sh = Now.Millisecond & Now.Second & Now.Month & Now.Minute & Now.Hour & Now.Year
                    sh += Mid(HttpContext.Current.Request.Files(0).FileName, InStrRev(HttpContext.Current.Request.Files(0).FileName, "."))
                    Dim filename As String = sh
                    HttpContext.Current.Request.Files(0).SaveAs(HttpContext.Current.Server.MapPath("/Images/" & filename))
                    user.taxi_photo = filename
                End If

                context.SaveChanges()
            End Using

            Return ConstructResponse(200, "OK", Nothing)

        End Function
        <PostParametrData({"username", "password"}, {GetType(String), GetType(String)})>
        Public Function WRAD_Login() As Dictionary(Of String, Object)

            Dim username As String = HttpContext.Current.Request("username")
            Dim password As String = HttpContext.Current.Request("password")

            Dim result As New Dictionary(Of String, Object)

            Using context As New TaxiEntities()

                Dim taxi As taxist = context.taxist.FirstOrDefault(Function(x) x.taxi_phone = username And x.taxi_password = password)

                If IsNothing(taxi) = False Then

                    Dim session As New WSession(HttpContext.Current)
                    session.Push("WRAD_AUTH", CType(True, String))
                    session.Push("taxi_id", taxi.taxi_id.ToString)
                    session.Push("taxi_phone", taxi.taxi_phone)
                    session.SaveChanes()

                    result.Add("taxist_id", taxi.taxi_id)

                    Dim tor As torders = taxi.torders.FirstOrDefault(Function(x) x.torder_status = 6)
                    If taxi.taxi_phoneconfirm = True And taxi.taxi_isacepted = False Then
                        session.Data.Clear()
                        Return ConstructResponse(500, "USER_BLOCKED", Nothing)
                    End If

                    If taxi.taxi_phoneconfirm = False Then
                        result.Add("NEED_PHONE_CONFIRM", 1)
                        'SendSms(taxi.taxi_phone, "Код подтверждения: " & taxi.last_code)
                    Else
                        result.Add("NEED_PHONE_CONFIRM", 0)
                    End If


                    If IsNothing(tor) = False Then
                        If tor.orders.order_create.Value.AddMinutes(CType(tor.orders.order_time, Double)).AddMinutes(10) < Now Then
                            tor.torder_status = 8
                            context.SaveChanges()
                            result.Add("current_order", 0)
                        Else
                            result.Add("current_order", 1)
                        End If
                    Else

                        result.Add("current_order", 0)
                    End If
                Else
                    Return ConstructResponse(500, "CANT_FIND_USER", Nothing)
                End If
            End Using
            Return ConstructResponse(200, "OK", result)

        End Function
        <NeedAuth, Description("Logout driver")>
        Public Function WRAD_Logout() As Dictionary(Of String, Object)

            Dim session As New WSession(HttpContext.Current)

            If File.Exists(HttpContext.Current.Server.MapPath("/Session/" & session.WID)) = True Then

                session.Data.Clear()

                File.Delete(HttpContext.Current.Server.MapPath("/Session/" & session.WID))

            End If

            Return ConstructResponse(200, "OK", Nothing)

        End Function
        <PostParametrData({"identiName", "Type", "PushID"}, {GetType(String), GetType(String), GetType(String)}), Description("Register phone for send push")>
        Public Function WRAD_UpdateOrRegisterClientPush() As Dictionary(Of String, Object)

            Dim identiName As String = HttpContext.Current.Request("identiName"), tpe As String = HttpContext.Current.Request("Type"), pushid As String = HttpContext.Current.Request("PushID")

            Using context As New TaxiEntities()

                If pushid = "" Or identiName = "" Or tpe = "" Then
                    Return ConstructResponse(500, "NEED_PARAMTRES", Nothing)
                End If

                Dim p As PushBase = context.PushBase.FirstOrDefault(Function(x) x.IdentitiName = identiName)

                If IsNothing(p) = True Then

                    p = New PushBase
                    p.device_id = Guid.NewGuid
                    p.IdentitiName = identiName
                    p.Type = tpe
                    p.ID = pushid
                    context.PushBase.Add(p)
                Else
                    p.ID = pushid
                End If

                context.SaveChanges()
            End Using
            Return ConstructResponse(200, "OK", Nothing)

        End Function
        <NeedAuth>
        Public Function Logout() As Dictionary(Of String, Object)
            Dim result As New Dictionary(Of String, Object)

            result.Add("result", "POKA")
            Dim session As New WSession(HttpContext.Current)

            session.Data.Clear()
            session.SaveChanes()

            Return ConstructResponse(200, "OK", result)

        End Function
        <PostParametrData({"phone"}, {GetType(String)}), Description("You can reset your password using this function. Just send mobile number. You can do it every 30 minutes")>
        Public Function ResetPassword() As Dictionary(Of String, Object)

            Dim session As New WSession(HttpContext.Current)

            If session.Data.ContainsKey("last_sms") = True Then
                Dim dt As DateTime = Date.Parse(session.Data("last_sms"))
                If dt.AddMinutes(30) > Now Then
                    Return ConstructResponse(500, "SMS_TIMEOUT", Nothing)
                End If
            End If


            Using context As New TaxiEntities()

                Dim tid As String

                Try

                    tid = HttpContext.Current.Request("phone")

                Catch ex As Exception

                    Return ConstructResponse(500, "BAD_GUID", Nothing)

                End Try

                Dim tx As taxist = context.taxist.FirstOrDefault(Function(x) x.taxi_phone = tid)

                Dim r As New Random

                If IsNothing(tx) = True Then

                    Return ConstructResponse(500, "CANT_FIND_USER", Nothing)

                Else

                    If IsNothing(tx.last_reser) = False Then

                        If tx.last_reser.Value.AddMinutes(30) > Now Then

                            Return ConstructResponse(500, "SMS_TIMEOUT", Nothing)

                        End If

                    End If

                    session.Push("last_sms", CType(Now, String))

                    SendSms(tx.taxi_phone, String.Format("Ваш пароль: {0}", tx.taxi_password))

                    tx.last_reser = Now

                    context.SaveChanges()

                    Return ConstructResponse(200, "OK", Nothing)

                End If
            End Using
        End Function
        <Description("Resend sms with acept code"), FunctionState(FunctionState.FState.Stable), NeedAuth>
        Public Function Resend() As Dictionary(Of String, Object)

            Dim session As New WSession(HttpContext.Current)

            If session.Data.ContainsKey("taxi_id") = False Then

                Return ConstructResponse(500, "CANT_START_SESSION", Nothing)

            End If

            If session.Data.ContainsKey("last_sms") = True Then

                Dim dt As DateTime = CType(session.Data("last_sms"), Date)

                If dt.AddMinutes(30) > Now Then

                    Return ConstructResponse(500, "SMS_TIMEOUT", Nothing)

                End If

            End If

            Using context As New TaxiEntities()

                Dim tid As Guid = Guid.Parse(session.Data("taxi_id"))

                Dim user As taxist = context.taxist.FirstOrDefault(Function(x) x.taxi_id = tid)

                Dim smsresult As String = SendSms(user.taxi_phone, String.Format("Код подтверждения: {0}", user.last_code))

                session.Push("last_sms", CType(Now, String))

                session.SaveChanes()

                If (smsresult = "OK") Then

                    user.last_reser = Now

                    context.SaveChanges()

                    Return ConstructResponse(200, "OK", Nothing)

                Else

                    Return ConstructResponse(500, String.Format("CAN'T SEND SMS: {0}", smsresult), Nothing)

                End If
            End Using

        End Function
        <PostParametrData({"code"}, {GetType(String)}), NeedAuth, Description("This function activate driver account by sended activation code, which it's must recive in sms")>
        Public Function ActivateUser() As Dictionary(Of String, Object)

            Dim result As New Dictionary(Of String, Object)

            Dim session As New WSession(HttpContext.Current)

            If session.Data.ContainsKey("taxi_id") = False Then
                Return ConstructResponse(500, "CANT_START_SESSION", Nothing)
            End If

            Using context As New TaxiEntities()
                Dim tid As Guid
                Dim code As Integer = CType(Val(HttpContext.Current.Request("code")), Integer)

                Try
                    tid = Guid.Parse(session.Data("taxi_id"))
                Catch ex As Exception
                    Return ConstructResponse(500, "BAD_GUID", Nothing)
                End Try


                Dim tx As taxist = context.taxist.FirstOrDefault(Function(x) x.taxi_id = tid)

                If IsNothing(tx) = False Then

                    If (tx.last_code <> code) Then
                        Return ConstructResponse(500, "BAD_CODE", Nothing)
                    Else
                        tx.taxi_isacepted = True
                        tx.taxi_phoneconfirm = True

                        context.SaveChanges()

                        result.Add("acepted", "true")
                    End If
                Else
                    Return ConstructResponse(500, "CANT_FIND_USER", Nothing)
                End If
            End Using
            Return ConstructResponse(200, "OK", result)

        End Function
        <PostParametrData({"client_id", "order_id", "rating_rate", "taxi_id", "taxi_text"}, {GetType(Guid), GetType(Guid), GetType(Integer), GetType(Guid), GetType(String)}), Description("When order is complited or faild client can add comment to this taxi driver. You need to send taxi_id and order_id")>
        Public Function AddComment() As Dictionary(Of String, Object)

            Try
                Dim rt As New rating

                Using context As New TaxiEntities()

                    Dim oderId As Guid = Guid.Parse(HttpContext.Current.Request("order_id"))
                    Dim clientId As Guid = Guid.Parse(HttpContext.Current.Request("client_id"))
                    Dim taxiId As Guid = Guid.Parse(HttpContext.Current.Request("taxi_id"))

                    If context.rating.Count(CType(Function(x) x.taxi_id = taxiId And x.client_id = clientId And x.order_id = oderId, Func(Of rating, Boolean))) <> 0 Then

                        Return ConstructResponse(500, "ORDER_COMMENT_EXIST", Nothing)

                    End If

                    Dim clientIdString As String

                    clientIdString = clientId.ToString

                    rt.order_id = oderId
                    rt.client_id = context.clients.FirstOrDefault(Function(x) x.client_udid = clientIdString).client_id
                    rt.rating_create = Now
                    rt.rating_id = Guid.NewGuid
                    rt.taxi_id = taxiId
                    rt.rating_rate = CType(Val(HttpContext.Current.Request("rating_rate")), Integer?)

                    rt.rating_text = HttpContext.Current.Request("taxi_text")

                    context.rating.Add(rt)

                    context.SaveChanges()

                    Dim result As New Dictionary(Of String, Object)

                    result.Add("rating", context.rating.Where(Function(x) x.taxi_id = taxiId).Average(Function(x) x.rating_rate))
                End Using
                Return ConstructResponse(200, "OK", Nothing)

            Catch ex As Exception
                Return ConstructResponse(500, ex.Message, Nothing)
            End Try

        End Function
        <FunctionState(FunctionState.FState.Stable), Description("Search city_id by coords"), PostParametrData({"coords"}, {GetType(String)})>
        Public Function GetCityId() As Dictionary(Of String, Object)

            Dim coords As String = HttpContext.Current.Request("coords")

            Dim crds() As String = Split(coords, ", ")

            Dim lat As Decimal = Decimal.Parse(crds(0).Replace(".", ","))
            Dim lng As Decimal = Decimal.Parse(crds(1).Replace(".", ","))


            Using context As New TaxiEntities

                Dim cities = context.cities.Where(
                    Function(x) x.city_position <> "").AsEnumerable().Where(
                    Function(x) IsNothing(x.city_position) = False).OrderBy(
                    Function(order)
                        Dim parms() As String = Split(order.city_position, ", ")
                        Dim lat1 As Decimal = Decimal.Parse(parms(0).Replace(".", ",")), long1 As Decimal = Decimal.Parse(parms(1).Replace(".", ","))
                        Return GetDistance(lat, lat1, lng, long1)
                    End Function).Take(1)


                For Each c In cities
                    Dim result As New Dictionary(Of String, Object)
                    result.Add("city_id", c.city_id)
                    result.Add("city_name", c.city_name)
                    result.Add("city_position", c.city_position)
                    Return ConstructResponse(200, "OK", result)
                Next
            End Using

            Return ConstructResponse(500, "NOT_FOUND", Nothing)

        End Function
        <Description("Return all cities")>
        Public Function GetAllCities() As Dictionary(Of String, Object)

            Using context As New TaxiEntities()

                Dim arr As New ArrayList

                Dim v = context.cities.Where(Function(x) 1 = 1)

                For Each c In v

                    Dim co As New Dictionary(Of String, Object)

                    co.Add("city_id", c.city_id)
                    co.Add("city_name", c.city_name)


                    arr.Add(co)

                Next
                Dim res As New Dictionary(Of String, Object)

                res.Add("cities", arr)

                Return ConstructResponse(200, "OK", res)
            End Using

        End Function
        <PostParametrData({"name"}, {GetType(String)})>
        Public Function AddCity() As String

            Return "NOT_USE"

            'Dim Name As String = HttpContext.Current.Request("name")

            'Dim cit As New cities

            'cit.city_id = Guid.NewGuid

            'cit.city_name = Name

            'Using _context As New TaxiEntities

            '    If IsNothing(_context.cities.FirstOrDefault(Function(x) x.city_name = Name)) = True Then

            '        _context.cities.Add(cit)

            '        _context.SaveChanges()

            '        _context.Dispose()

            '        Return cit.city_id.ToString
            '    Else

            '        Return _context.cities.FirstOrDefault(Function(x) x.city_name = Name).city_id.ToString

            '    End If
            'End Using

        End Function
        <PostParametrData({"taxi_id"}, {GetType(Guid)})>
        Public Function GetTaxiProfile() As Dictionary(Of String, Object)

            Dim result As New Dictionary(Of String, Object)

            Using context As New TaxiEntities()

                Dim tid As Guid

                Try
                    tid = Guid.Parse(HttpContext.Current.Request("taxi_id"))

                Catch ex As Exception

                    Return ConstructResponse(500, "BAD_GUID", Nothing)

                End Try

                Dim tx As taxist = context.taxist.FirstOrDefault(Function(x) x.taxi_id = tid)

                If (IsNothing(tx) = True) Then

                    Return ConstructResponse(500, "TAXIST_NOT_FOUND", Nothing)

                End If

                If IsNothing(tx) = False Then

                    Dim c As New Dictionary(Of String, Object)

                    c.Add("city_id", tx.cities.city_id)
                    c.Add("city_name", tx.cities.city_name)

                    result.Add("city", c)
                    result.Add("taxi_carnumber", tx.taxi_carnumber)
                    result.Add("taxi_color", tx.taxi_color)
                    result.Add("taxi_created", tx.taxi_created)
                    result.Add("taxi_id", tx.taxi_id)
                    result.Add("taxi_isonline", tx.taxi_isonline)
                    result.Add("taxi_lastname", tx.taxi_lastname)
                    result.Add("taxi_location", tx.taxi_location)
                    result.Add("taxi_marka", tx.taxi_marka)
                    result.Add("taxi_model", tx.taxi_model)
                    result.Add("taxi_phone", tx.taxi_phone)
                    result.Add("taxt_firstname", tx.taxt_firstname)

                    If tx.taxi_photo <> "" Then result.Add("taxi_photo", String.Format("/Images/{0}", tx.taxi_photo)) Else result.Add("taxi_photo", "")
                    If tx.rating.Count <> 0 Then result.Add("taxi_rating", tx.rating.Average(Function(x) x.rating_rate)) Else result.Add("taxi_rating", 0)
                    result.Add("taxi_rating_count", tx.rating.Count)


                    Dim clientBalance As Integer
                    If IsNothing(context.transfers.Where(Function(x) x.client_id = tid)) = False Then
                        If context.transfers.Where(Function(x) x.client_id = tid).Count <> 0 Then
                            clientBalance = CType(context.transfers.Where(Function(x) x.client_id = tid).Sum(Function(x) x.transfer_amount), Integer)
                        Else
                            clientBalance = 0
                        End If
                    Else
                        clientBalance = 0
                    End If

                    result.Add("client_balance", clientBalance)
                    Return ConstructResponse(200, "OK", result)
                Else
                    Return ConstructResponse(500, "NOT_FOUND", Nothing)
                End If
            End Using

        End Function
        <PostParametrData({"order_id"}, {GetType(Guid)}), Description("Return order information by it's id")>
        Public Function GetOrderById() As Dictionary(Of String, Object)

            Dim result As New Dictionary(Of String, Object)

            Try
                Dim oid As Guid = Guid.Parse(HttpContext.Current.Request("order_id"))

                Using context As New TaxiEntities()

                    Dim order As orders = context.orders.FirstOrDefault(Function(x) x.order_id = oid)

                    result.Add("client_id", order.client_id)
                    result.Add("order_comment", order.order_comment)
                    result.Add("order_create", order.order_create.Value.ToString)
                    result.Add("order_from_address", order.order_from_address)
                    result.Add("order_from_location", order.order_from_location)
                    result.Add("order_status", order.order_status)
                    result.Add("order_time", order.order_time)
                    result.Add("order_to_address", order.order_to_address)
                    result.Add("order_to_location", order.order_to_location)
                    result.Add("order_user_phone", order.order_user_phone)

                    Dim tx As torders = context.torders.FirstOrDefault(Function(x) x.order_id = order.order_id And (x.torder_status = 6 Or x.torder_status = 7 Or x.torder_status = 8))

                    If IsNothing(tx) = False Then

                        result.Add("taxi_id", tx.taxi_id)
                        result.Add("torder_price", tx.torder_price)
                        result.Add("torder_status", tx.torder_status)

                    Else

                        result.Add("taxi_id", Nothing)
                        result.Add("torder_price", 0)
                        result.Add("torder_status", Nothing)

                    End If

                    result.Add("taxi_arrived", Not IsNothing(context.torders.FirstOrDefault(Function(x) x.order_id = order.order_id And x.torder_taxi_arrived = True And x.torder_status >= 6)))

                    Return ConstructResponse(200, "OK", result)
                End Using

            Catch ex As NullReferenceException
                Return ConstructResponse(500, "ORDER_NOT_EXIST", Nothing)
            Catch ex As Exception
                Return ConstructResponse(500, ex.Message, Nothing)
            End Try

        End Function
        <Description("Return information about single order")>
        Public Function GetOrderInformation(order_id As String) As Dictionary(Of String, Object)

            Dim result As New Dictionary(Of String, Object)

            Using context As New TaxiEntities()



                Dim ordId As Guid = Guid.Parse(order_id)

                Dim odr As orders = context.orders.FirstOrDefault(Function(x) x.order_id = ordId)

                If IsNothing(odr) = True Then

                    Return ConstructResponse(500, "CANT_FIND_ORDER", Nothing)

                End If

                result.Add("client_id", odr.client_id)
                result.Add("order_comment", odr.order_comment)
                result.Add("order_create", odr.order_create.Value.ToString)
                result.Add("order_from_address", odr.order_from_address)
                result.Add("order_from_location", odr.order_from_location)
                result.Add("order_id", odr.order_id)
                result.Add("order_status", odr.order_status)
                result.Add("order_time", odr.order_time)
                result.Add("order_to_address", odr.order_to_address)
                result.Add("order_to_location", odr.order_to_location)
                result.Add("order_user_phone", odr.order_user_phone)

                Return result
            End Using

        End Function
        <FunctionState(FunctionState.FState.Stable), NeedAuth, Description("Driver can say no for request"), PostParametrData({"order_id"}, {GetType(Guid)})>
        Public Function SayNo() As Dictionary(Of String, Object)

            Using context As New TaxiEntities()

                Dim session As New WSession(HttpContext.Current)

                Dim goi As Guid = Guid.Parse(HttpContext.Current.Request("order_id"))
                Dim tid As Guid = Guid.Parse(session.Data("taxi_id"))

                Dim txt As torders = context.torders.FirstOrDefault(Function(x) x.order_id = goi And x.taxi_id = tid)

                If IsNothing(txt) = False Then

                    txt.torder_status = 4

                    context.SaveChanges()

                End If

            End Using
            Return ConstructResponse(200, "OK", Nothing)

        End Function
        <FunctionState(FunctionState.FState.Stable), Description("Client can delete order before it's accepted"), PostParametrData({"order_id"}, {GetType(Guid)})>
        Public Function DeleteOrder() As Dictionary(Of String, Object)

            Dim oid As Guid = Guid.Parse(HttpContext.Current.Request("order_id"))

            Using context As New TaxiEntities()

                Dim ord As orders = context.orders.FirstOrDefault(Function(x) x.order_id = oid)

                If IsNothing(ord) = True Then

                    Return ConstructResponse(500, "CANT_FIND_ORDER", Nothing)

                End If

                Dim tor As torders = ord.torders.FirstOrDefault(Function(x) x.torder_status = 6)

                If IsNothing(tor) = False Then

                    Return ConstructResponse(500, "HAS_ACEPTED_DRIVERS", Nothing)

                End If

                Dim ttrs = context.torders.Where(Function(x) x.order_id = oid)

                For Each t As torders In ttrs

                    context.torders.Remove(t)

                Next

                context.SaveChanges()
                context.orders.Remove(ord)
                context.SaveChanges()

            End Using
            Return ConstructResponse(200, "OK", Nothing)

        End Function
        <FunctionState(FunctionState.FState.Stable), Description("Get driver coodrinates by order id"), PostParametrData({"order_id"}, {GetType(Guid)})>
        Public Function GetTaxiLocation() As Dictionary(Of String, Object)

            Dim loc As New Dictionary(Of String, Object)

            Dim oid As Guid = Guid.Parse(HttpContext.Current.Request("order_id"))

            Using context As New TaxiEntities()

                Dim ord As orders = context.orders.FirstOrDefault(Function(x) x.order_id = oid)

                If IsNothing(ord) = True Then

                    Return ConstructResponse(500, "CANT_FIND_ORDER", Nothing)

                End If

                Dim tor As torders = ord.torders.FirstOrDefault(Function(x) x.torder_status = 6)

                If IsNothing(tor) = True Then

                    Return ConstructResponse(500, "NO_ACEPTED_DRIVERS", Nothing)

                End If

                Dim lastdate As DateTime = ord.order_create.Value.AddMinutes(ord.order_time)
                Dim curdate As DateTime = Now
                Dim dif As TimeSpan = lastdate - curdate

                loc.Add("timeleft", dif)

                loc.Add("location", tor.taxist.taxi_location)

                loc.Add("taxi_arrived", tor.torder_taxi_arrived)

                Return ConstructResponse(200, "OK", loc)
            End Using
        End Function
        <Description("Driver can set price for order"), NeedAuth, HideData>
        Public Function SetPrice(orderId As String, price As Integer) As Dictionary(Of String, Object)

            Dim session As New WSession(HttpContext.Current)

            If session.Data.ContainsKey("taxi_id") = False Then

                Return ConstructResponse(500, "CONT_START_SESSION", Nothing)

            End If

            Dim goi As Guid = Guid.Parse(orderId)
            Dim gti As Guid = Guid.Parse(session.Data("taxi_id"))

            Using context As New TaxiEntities()

                If context.torders.Count(Function(x) x.order_id = goi And x.torder_status = 6) > 0 Then

                    Return ConstructResponse(500, "CLIENT_SELECT_ANOTHER_DRIVER", Nothing)

                End If

                Dim torder As torders = context.torders.FirstOrDefault(Function(x) x.order_id = goi And x.taxi_id = gti)

                If torder.torder_created.AddSeconds(95) < Now Then

                    Return ConstructResponse(500, "TIMEOUT", Nothing)

                End If

                If IsNothing(torder) = True Then

                    Return ConstructResponse(500, "CONT_FIND_TORDER", Nothing)

                End If

                If torder.torder_status <> 0 Then

                    Return ConstructResponse(500, "TORDER_STATUS_NOT_0", Nothing)

                End If

                If torder.orders.order_status <> 0 Then

                    Return ConstructResponse(500, "ORDER_STATUS_CLOSED", Nothing)

                End If

                torder.torder_price = price

                torder.torder_status = 1
                torder.torder_update = Now
                context.SaveChanges()
            End Using
            Return ConstructResponse(200, "OK", Nothing)

        End Function
        <FunctionState(FunctionState.FState.Stable), Description("If driver not come at time, client can say about it"), PostParametrData({"order_id"}, {GetType(Guid)})>
        Public Function NoDriver() As Dictionary(Of String, Object)

            Dim oid As Guid = Guid.Parse(HttpContext.Current.Request("order_id"))

            Using context As New TaxiEntities()

                Dim ord As orders = context.orders.FirstOrDefault(Function(x) x.order_id = oid)
                If IsNothing(ord) = True Then
                    Return ConstructResponse(500, "CANT_FIND_ORDER", Nothing)
                End If

                Dim tor As torders = ord.torders.FirstOrDefault(Function(x) x.torder_status = 6)
                If IsNothing(tor) = True Then
                    Return ConstructResponse(500, "NO_ACEPTED_DRIVERS", Nothing)
                End If

                If ord.order_create.Value.AddMinutes(CType(ord.order_time, Double)) > Now Then
                    Return ConstructResponse(500, "TIME_NOT_LEFT", Nothing)
                End If

                tor.torder_status = 8
                ord.order_status = False

                context.SaveChanges()
            End Using
            Return ConstructResponse(200, "OK", Nothing)
        End Function
        <FunctionState(FunctionState.FState.Stable), Description("This function send push notification to client"), PostParametrData({"order_id"}, {GetType(Guid)})>
        Public Function DriverCome() As Dictionary(Of String, Object)

            Dim tmps As New Dictionary(Of String, Object)
            Dim oid As Guid = Guid.Parse(HttpContext.Current.Request("order_id"))

            Using context As New TaxiEntities()

                Dim ord As orders = context.orders.FirstOrDefault(Function(x) x.order_id = oid)
                If IsNothing(ord) = True Then
                    Return ConstructResponse(500, "CANT_FIND_ORDER", Nothing)
                End If

                Dim tor As torders = ord.torders.FirstOrDefault(Function(x) x.torder_status = 6)
                If IsNothing(tor) = True Then
                    Return ConstructResponse(500, "NO_ACEPTED_DRIVERS", Nothing)
                End If

                tor.torder_taxi_arrived = True

                Dim client As New clients
                client = context.clients.FirstOrDefault(Function(x) x.client_udid = tor.clients.client_udid)
                If IsNothing(client) = False Then

                    Dim cu As String = client.client_udid
                    Dim pb As PushBase = context.PushBase.FirstOrDefault(Function(x) x.IdentitiName = cu)
                    Dim WPS As New WRADA_PUSH_SERVICE

                    If IsNothing(pb) = False Then
                        Select Case (Trim(pb.Type))
                            Case "parse"
                                WPS.SendParseNotification(pb.ID, "SmartTaxi", "Водитель приехал", String.Format("a_{0}", ord.order_id.ToString))
                            Case "GCM"
                                WPS.SendGCMNotification(pb.ID, "SmartTaxi", ord.order_id.ToString, "Водитель приехал")
                        End Select
                    End If
                End If

                context.SaveChanges()

                Return ConstructResponse(200, "OK", tmps)
            End Using
        End Function
        <FunctionState(FunctionState.FState.Stable), Description("This function continue order for 10 minutes"), PostParametrData({"order_id"}, {GetType(Guid)})>
        Public Function ResumeOrder() As Dictionary(Of String, Object)

            Dim oid As Guid = Guid.Parse(HttpContext.Current.Request("order_id"))

            Using context As New TaxiEntities()

                Dim ord As orders = context.orders.FirstOrDefault(Function(x) x.order_id = oid)
                If IsNothing(ord) = True Then
                    Return ConstructResponse(500, "CANT_FIND_ORDER", Nothing)
                End If

                ord.order_time += 10

                context.SaveChanges()
            End Using
            Return ConstructResponse(200, "OK", Nothing)

        End Function
        <FunctionState(FunctionState.FState.Stable), Description("This function send push notification to client for rating"), PostParametrData({"order_id"}, {GetType(Guid)})>
        Public Function OrderComplite() As Dictionary(Of String, Object)

            Using context As New TaxiEntities()

                Dim oid As Guid = Guid.Parse(HttpContext.Current.Request("order_id"))

                Dim ord As orders = context.orders.FirstOrDefault(Function(x) x.order_id = oid)
                If IsNothing(ord) = True Then
                    Return ConstructResponse(500, "CANT_FIND_ORDER", Nothing)
                End If

                Dim tor As torders = ord.torders.FirstOrDefault(Function(x) x.torder_status = 6)
                If IsNothing(tor) = True Then
                    Return ConstructResponse(500, "NO_ACEPTED_DRIVERS", Nothing)
                End If

                If tor.torder_taxi_arrived = False Then
                    Return ConstructResponse(500, "DRIVER_NOT_COME", Nothing)
                End If

                tor.torder_status = 7

                Dim client As clients
                client = context.clients.FirstOrDefault(Function(x) x.client_udid = tor.clients.client_udid)

                If IsNothing(client) = False Then
                    Dim pb As PushBase = context.PushBase.FirstOrDefault(Function(x) x.IdentitiName = client.client_udid)
                    Dim WPS As New WRADA_PUSH_SERVICE

                    If IsNothing(pb) = False Then
                        Select Case (Trim(pb.Type))
                            Case "parse"
                                WPS.SendParseNotification(pb.ID, "SmartTaxi", "Заказ выполнен оцените водителя", String.Format("b_{0}", ord.order_id.ToString))
                            Case "GCM"
                                WPS.SendGCMNotification(pb.ID, "SmartTaxi", ord.order_id.ToString, "Заказ выполнен оцените водителя")
                        End Select
                    End If
                End If

                ord.order_status = False

                context.SaveChanges()
            End Using
            Return ConstructResponse(200, "OK", Nothing)

        End Function
        <FunctionState(FunctionState.FState.Stable), Description("After recive requests, client can acept"), PostParametrData({"order_id", "taxi_id", "is_accept", "phone"}, {GetType(Guid), GetType(Guid), GetType(Integer), GetType(String)})>
        Public Function ClientAnswer() As Dictionary(Of String, Object)

            Dim goi As Guid = Guid.Parse(HttpContext.Current.Request("order_id"))
            Dim tid As Guid = Guid.Parse(HttpContext.Current.Request("taxi_id"))
            Dim isa As Integer = CType(Val(HttpContext.Current.Request("is_accept")), Integer)
            Dim phone As String = HttpContext.Current.Request("phone")
            Using context As New TaxiEntities()

                Dim order As orders = context.orders.FirstOrDefault(Function(x) x.order_id = goi)
                If IsNothing(order) = True Then
                    Return ConstructResponse(500, "ORDER_NOT_EXISTS", Nothing)
                End If

                If order.order_status = False Then
                    Return ConstructResponse(500, "ORDER_CLOSED", Nothing)
                End If

                Dim tord = context.torders.FirstOrDefault(Function(x) x.order_id = goi And (x.torder_status < 2) And x.taxi_id = tid)
                If IsNothing(tord) = True Then
                    Return ConstructResponse(500, "CANT_WORK_WITH_TORDER", Nothing)
                End If

                If (tord.torder_status <> 1) Then Return ConstructResponse(500, "BAD_STATUS", Nothing)

                If context.torders.Where(Function(x) x.taxi_id = tid And x.torder_status = 6).ToList.AsEnumerable.Where(Function(x) x.orders.order_create.Value.AddMinutes(x.orders.order_time).AddMinutes(10) > Now).Count > 0 Then
                    Return ConstructResponse(500, "TAXI_BUSI", Nothing)
                End If

                Dim clientBalance As Integer = CType(context.transfers.Where(Function(x) x.client_id = tid).Sum(Function(x) x.transfer_amount), Integer)

                If isa = 1 Then
                    If clientBalance - (tord.torder_price * 0.05) < 0 Then
                        tord.torder_status = 3
                        Return ConstructResponse(500, "TAXIST_BICH", Nothing)
                    End If

                    Dim tr As New transfers
                    tr.transfer_amount = CType((-1 * (tord.torder_price * 0.05)), Decimal?)
                    tr.transfer_code = "Комиссия"
                    tr.transfer_date = Now
                    tr.transfer_id = Guid.NewGuid
                    tr.transfer_sdate = Now.ToString
                    tr.txt_id = ""
                    tr.client_id = tord.taxi_id
                    context.transfers.Add(tr)

                    tord.torder_status = 6
                    tord.orders.order_user_phone = phone

                    context.SaveChanges()
                    Return ConstructResponse(200, "OK", Nothing)
                Else
                    Return ConstructResponse(500, "YOU_CANT_SAY_NO", Nothing)
                End If
            End Using

        End Function

        <FunctionState(FunctionState.FState.Stable), Description("Function For Driver. It's set price"), PostParametrData({"order_id", "price"}, {GetType(Guid), GetType(Integer)})>
        Public Function MakeResponse() As Dictionary(Of String, Object)

            Using context As New TaxiEntities()

                Dim goi As Guid = Guid.Parse(HttpContext.Current.Request("order_id"))
                Dim price As Integer = CType(Val(HttpContext.Current.Request("price")), Integer)
                Dim session As New WSession(HttpContext.Current)

                If price = 0 Then
                    Return ConstructResponse(500, "BAD_PRICE", Nothing)
                End If

                Dim order As orders = context.orders.FirstOrDefault(Function(x) x.order_id = goi)

                If IsNothing(order) = True Then
                    Return ConstructResponse(500, "ORDER_NOT_EXIST", Nothing)
                End If

                If (order.order_status = 1) Then
                    Return ConstructResponse(500, "ORDER_CLOSED", Nothing)
                End If

                If IsNothing(order.torders.FirstOrDefault(Function(x) x.torder_status >= 6 And x.order_id = goi)) = False Then
                    Return ConstructResponse(500, "TOO_LATE", Nothing)
                End If

                Dim tid As Guid = Guid.Parse(session.Data("taxi_id"))

                Dim tord As torders = context.torders.FirstOrDefault(Function(x) x.order_id = order.order_id And x.taxi_id = tid)

                If IsNothing(tord) = True Then
                    Return ConstructResponse(500, "HAVE_NO_REQUEST", Nothing)
                End If

                If tord.torder_update.Value.AddSeconds(95) < Now Then
                    Return ConstructResponse(500, "TOO_LATE", Nothing)
                End If

                If tord.torder_price <> 0 Then
                    Return ConstructResponse(500, "ALRADY_SETED", Nothing)
                End If

                Dim clientBalance As Integer = CType(context.transfers.Where(Function(x) x.client_id = tid).Sum(Function(x) x.transfer_amount), Integer)

                If clientBalance - (price * 0.05) < 0 Then

                    Return ConstructResponse(500, "YOU_BICH", Nothing)

                End If

                tord.torder_price = price
                tord.torder_status = 1
                tord.torder_update = Now

                context.SaveChanges()
            End Using
            Return ConstructResponse(200, "OK", Nothing)

        End Function

        <PostParametrData({"taxi_id", "order_id"}, {GetType(Guid), GetType(Guid)})>
        Public Function GetLastTime() As Dictionary(Of String, Object)
            Try

                Dim taxiId As Guid = Guid.Parse(HttpContext.Current.Request("taxi_id"))
                Dim orderId As Guid = Guid.Parse(HttpContext.Current.Request("order_id"))

                Using context As New TaxiEntities()

                    'GetContext()

                    Dim tOrder As torders = context.torders.FirstOrDefault(Function(x) x.taxi_id = taxiId And x.order_id = orderId)
                    If IsNothing(tOrder) = True Then
                        Return ConstructResponse(500, "NOT_EXIST", Nothing)
                    Else
                        Dim result As New Dictionary(Of String, Object)
                        result.Add("timeleft", Val((tOrder.torder_created.AddSeconds(95) - Now).TotalSeconds))
                        Return (ConstructResponse(200, "OK", result))
                    End If
                End Using
            Catch ex As Exception
                Return ConstructResponse(500, ex.Message, Nothing)
            End Try

        End Function

        <NeedAuth, Description("Return list with detail information about my orders")>
        Public Function GetMyOrders() As Dictionary(Of String, Object)

            Using context As New TaxiEntities()
                Try

                    Dim session As New WSession(HttpContext.Current)
                    If session.Data.ContainsKey("taxi_id") = False Then
                        Return ConstructResponse(500, "CANT_START_SESSION", Nothing)
                    End If

                    Dim gid As Guid = Guid.Parse(session.Data("taxi_id"))


                    Dim result As New List(Of Dictionary(Of String, Object))

                    Dim allOrders = context.torders.Where(Function(x) x.taxi_id = gid And ((x.torder_status = 0) Or (x.torder_status = 1) Or (x.torder_status = 6)))
                    For Each t In allOrders
                        If t.torder_status = 0 Then
                            If t.torder_update.Value.AddSeconds(95) < Now Then
                                t.torder_status = 3
                                Continue For
                            End If
                        ElseIf t.torder_status = 1 Then
                            If t.torder_update.Value.AddSeconds(180) < Now Then
                                t.torder_status = 5
                                Continue For
                            End If
                        ElseIf t.torder_status = 6 Then
                            If t.orders.order_status = False Then
                                Dim tmpt As torders = context.torders.FirstOrDefault(Function(x) x.torder_id = t.torder_id)
                                tmpt.torder_status = 4
                                Continue For
                            End If

                            If t.orders.order_create.Value.AddMinutes(CType(t.orders.order_time, Double)).AddMinutes(10) < Now Then
                                Dim tmpt As torders = context.torders.FirstOrDefault(Function(x) x.torder_id = t.torder_id)
                                tmpt.torder_status = 5
                                Continue For
                            End If

                            Dim tmp As New Dictionary(Of String, Object)

                            tmp.Add("client_id", t.client_id)
                            tmp.Add("order_id", t.order_id)
                            tmp.Add("taxi_id", t.taxi_id)
                            tmp.Add("torder_created", t.torder_created.ToString)
                            tmp.Add("torder_id", t.torder_id)
                            tmp.Add("torder_price", t.torder_price)
                            tmp.Add("torder_status", t.torder_status)
                            tmp.Add("torder_taxi_arrived", Not IsNothing(context.torders.FirstOrDefault(Function(x) x.order_id = t.order_id And x.torder_taxi_arrived = True And x.torder_status >= 6)))

                            tmp.Add("order_from_address", t.orders.order_from_address)
                            tmp.Add("order_from_location", t.orders.order_from_location)
                            tmp.Add("order_comment", t.orders.order_comment)
                            tmp.Add("order_create", t.orders.order_create.Value.ToString.ToString)
                            tmp.Add("order_time", t.orders.order_time)
                            tmp.Add("order_to_address", t.orders.order_to_address)
                            tmp.Add("order_to_location", t.orders.order_to_location)
                            tmp.Add("order_user_phone", t.orders.order_user_phone)

                            result.Add(tmp)
                        End If
                    Next

                    'Dim ator3 = _context.torders.Where(Function(x) x.taxi_id = gid And (x.torder_status = 0))
                    'For Each t In ator3
                    '    If t.torder_update.Value.AddSeconds(95) < Now Then
                    '        t.torder_status = 3
                    '        Continue For
                    '    End If
                    'Next

                    'Dim ator2 = _context.torders.Where(Function(x) x.taxi_id = gid And (x.torder_status = 1))
                    'For Each t In ator2
                    '    If t.torder_update.Value.AddSeconds(180) < Now Then
                    '        t.torder_status = 5
                    '        Continue For
                    '    End If
                    'Next


                    'Dim ator = _context.torders.Where(Function(x) x.taxi_id = gid And (x.torder_status = 6))
                    'For Each t In ator
                    '    If t.orders.order_status = False Then
                    '        Dim tmpt As torders = _context.torders.FirstOrDefault(Function(x) x.torder_id = t.torder_id)
                    '        tmpt.torder_status = 4
                    '        Continue For
                    '    End If

                    '    If t.orders.order_create.Value.AddMinutes(t.orders.order_time).AddMinutes(10) < Now Then
                    '        Dim tmpt As torders = _context.torders.FirstOrDefault(Function(x) x.torder_id = t.torder_id)
                    '        tmpt.torder_status = 5
                    '        Continue For
                    '    End If

                    '    Dim tmp As New Dictionary(Of String, Object)

                    '    tmp.Add("client_id", t.client_id)
                    '    tmp.Add("order_id", t.order_id)
                    '    tmp.Add("taxi_id", t.taxi_id)
                    '    tmp.Add("torder_created", t.torder_created.ToString)
                    '    tmp.Add("torder_id", t.torder_id)
                    '    tmp.Add("torder_price", t.torder_price)
                    '    tmp.Add("torder_status", t.torder_status)
                    '    tmp.Add("torder_taxi_arrived", Not IsNothing(_context.torders.FirstOrDefault(Function(x) x.order_id = t.order_id And x.torder_taxi_arrived = True And x.torder_status >= 6)))

                    '    tmp.Add("order_from_address", t.orders.order_from_address)
                    '    tmp.Add("order_from_location", t.orders.order_from_location)
                    '    tmp.Add("order_comment", t.orders.order_comment)
                    '    tmp.Add("order_create", t.orders.order_create.Value.ToString.ToString)
                    '    tmp.Add("order_time", t.orders.order_time)
                    '    tmp.Add("order_to_address", t.orders.order_to_address)
                    '    tmp.Add("order_to_location", t.orders.order_to_location)
                    '    tmp.Add("order_user_phone", t.orders.order_user_phone)

                    '    result.Add(tmp)
                    'Next

                    If result.Count <> 0 Then
                        Dim tprersult As New Dictionary(Of String, Object)
                        tprersult.Add("orders", result)
                        Return ConstructResponse(200, "OK", tprersult)
                    End If



                    Dim ts = context.torders.Where(CType(Function(x) x.taxi_id = gid And x.torder_status = 0 And x.orders.order_status <> 1, Func(Of torders, Boolean))).AsEnumerable().Where(Function(x) x.torder_created.AddSeconds(95) < Now)
                    For Each t In ts
                        Dim tmp As torders = context.torders.FirstOrDefault(Function(x) x.torder_id = t.torder_id)
                        tmp.torder_status = 2
                    Next

                    Dim ts2 = context.torders.Where(Function(x) x.taxi_id = gid And x.torder_status = 1).AsEnumerable().Where(Function(x) x.torder_created.AddSeconds(180) < Now)
                    For Each t In ts2
                        Dim tmp As torders = context.torders.FirstOrDefault(Function(x) x.torder_id = t.torder_id)
                        tmp.torder_status = 5
                    Next

                    Dim tor = context.torders.Where(
                        Function(x) x.taxi_id = gid And x.torder_status < 2).AsEnumerable().Where(
                        Function(x)
                            Return True
                        End Function).Where(
                        Function(x)
                            Return x.orders.order_create.Value.AddMinutes(CType(x.orders.order_time, Double)).AddMinutes(10) > Now
                        End Function).OrderBy(
                        Function(x) x.torder_status)

                    For Each t As torders In tor
                        Dim tmp As New Dictionary(Of String, Object)
                        tmp.Add("client_id", t.client_id)
                        tmp.Add("order_id", t.order_id)
                        tmp.Add("taxi_id", t.taxi_id)
                        tmp.Add("torder_created", t.torder_created.ToString)
                        tmp.Add("torder_id", t.torder_id)
                        tmp.Add("torder_price", t.torder_price)
                        tmp.Add("torder_status", t.torder_status)
                        tmp.Add("torder_taxi_arrived", Not IsNothing(context.torders.FirstOrDefault(Function(x) x.order_id = t.order_id And x.torder_taxi_arrived = True And x.torder_status >= 6)))

                        tmp.Add("order_from_address", t.orders.order_from_address)
                        tmp.Add("order_from_location", t.orders.order_from_location)
                        tmp.Add("order_comment", t.orders.order_comment)
                        tmp.Add("order_create", t.orders.order_create.Value.ToString)
                        tmp.Add("order_time", t.orders.order_time)
                        tmp.Add("order_to_address", t.orders.order_to_address)
                        tmp.Add("order_to_location", t.orders.order_to_location)
                        tmp.Add("order_user_phone", t.orders.order_user_phone)

                        result.Add(tmp)
                    Next

                    Dim prersult As New Dictionary(Of String, Object)

                    prersult.Add("orders", result)
                    context.SaveChanges()

                    Return ConstructResponse(200, "OK", prersult)

                Catch ex As Exception

                    Dim erro As String = String.Format("{0} ({1}).", ex.Message, ex.StackTrace)

                    Dim tmp As Exception
                    tmp = ex.InnerException

                    While IsNothing(tmp) = False
                        erro += String.Format(" {0}({1})", tmp.Message, tmp.StackTrace)
                        tmp = tmp.InnerException
                    End While

                    context.SaveChanges()

                    Return ConstructResponse(500, erro, Nothing)
                End Try
            End Using
        End Function

        <Description("Will be found the next three drivers"), HideData>
        Public Function GetNearest(ByVal _orderId As String, city_id As String, Optional howMach As String = "6") As IEnumerable

            Dim result As New Dictionary(Of String, Object)

            Try
                Using context As New TaxiEntities()

                    Dim cityid As Guid = Guid.Parse(city_id)
                    Dim orderId As Guid = Guid.Parse(_orderId)
                    Dim order As orders = context.orders.FirstOrDefault(Function(x) x.order_id = orderId)

                    If IsNothing(order) = True Then
                        Return ConstructResponse(500, "ORDER_NOT_EXIST", Nothing)
                    End If

                    Dim taxists = context.taxist.AsEnumerable.Where(
                        Function(x)
                            Return CType((x.torders.AsEnumerable.Count(Function(y) y.taxi_id = x.taxi_id And y.order_id = orderId) = 0 _
                                          And IsNothing(x.taxi_location) = False _
                                          And x.city_id = cityid _
                                          And x.taxi_isonline = True _
                                          And x.taxi_isacepted = True), Boolean)
                        End Function).Where(
                        Function(x) x.taxi_location <> "").AsEnumerable().OrderBy(
                            Function(yx)
                                Dim parms() As String = Split(yx.taxi_location, ", ")
                                Dim parms2() As String = Split(order.order_from_location, ", ")

                                Dim lat1 As Decimal = Decimal.Parse(parms(0).Replace(".", ",")), long1 As Decimal = Decimal.Parse(parms(1).Replace(".", ","))
                                Dim lat2 As Decimal = Decimal.Parse(parms2(0).Replace(".", ",")), long2 As Decimal = Decimal.Parse(parms2(1).Replace(".", ","))

                                Return GetDistance(lat1, lat2, long1, long2)
                            End Function).Take(Val(howMach)).Select(
                        Function(x)
                            Return New Drivers With {.city_id = x.city_id, _
                                              .taxi_carnumber = x.taxi_carnumber, _
                                              .taxi_color = x.taxi_color, _
                                              .taxi_id = x.taxi_id, _
                                              .taxi_lastname = x.taxi_lastname, _
                                              .taxi_location = x.taxi_location, _
                                              .taxi_marka = x.taxi_marka, _
                                              .taxi_model = x.taxi_model, _
                                              .taxi_photo = "/Images/" & x.taxi_photo, _
                                              .taxt_firstname = x.taxt_firstname, _
                                              .rating = 0, _
                                                     .price = 0
                                                  }
                        End Function).AsEnumerable.ToList


                    For i As Integer = 0 To taxists.Count - 1
                        Dim tor As New torders
                        tor.order_id = orderId
                        tor.client_id = order.client_id
                        tor.taxi_id = taxists.ToList()(i).taxi_id
                        tor.torder_created = Now
                        tor.torder_id = Guid.NewGuid
                        tor.torder_status = 0
                        tor.torder_price = 0
                        tor.torder_taxi_arrived = False
                        tor.torder_update = Now
                        tor.torder_taxi_arrived = False

                        context.torders.Add(tor)
                    Next

                    context.SaveChanges()

                    Return taxists
                End Using
            Catch ex As Exception
                Return ConstructResponse(500, ex.InnerException.InnerException.Message, Nothing)
            End Try

        End Function

        <Description("The first time a client connects, it must call this function to register it in the system."), PostParametrData({"udid", "location"}, {GetType(Guid), GetType(String)})>
        Public Function ClientConnect() As Dictionary(Of String, Object)

            Dim udid As Guid = Guid.Parse(HttpContext.Current.Request("udid"))
            Dim result As New Dictionary(Of String, Object)

            result.Add("order_id", Nothing)

            Try

                Using context As New TaxiEntities()

                    If IsNothing(context.clients.FirstOrDefault(Function(x) x.client_udid = udid.ToString)) = True Then

                        udid = Guid.Parse(HttpContext.Current.Request("udid").ToUpper)

                        Dim client As New clients
                        client.client_created = Now
                        client.client_id = Guid.NewGuid

                        If IsNothing(HttpContext.Current.Request("location")) = False Then

                            client.client_location = HttpContext.Current.Request("location")

                        Else

                            client.client_location = ""

                        End If

                        client.client_udid = UCase(udid.ToString)
                        context.clients.Add(client)
                        context.SaveChanges()
                    Else

                        udid = Guid.Parse(HttpContext.Current.Request("udid"))

                        Dim tax As clients = context.clients.FirstOrDefault(Function(x) x.client_udid = udid.ToString)

                        If IsNothing(HttpContext.Current.Request("location")) = False Then

                            tax.client_location = HttpContext.Current.Request("location")

                        End If

                        Dim ooo = context.orders.Where(CType(Function(x) x.client_id = tax.client_id And x.order_status = True, Func(Of orders, Boolean)))

                        If IsNothing(ooo) = False Then

                            If ooo.Count <> 0 Then

                                For Each r In ooo
                                    If r.torders.Where(Function(x) x.torder_status = 6).Count = 0 Then

                                        r.order_status = 0

                                    Else

                                        If r.order_create.Value.AddMinutes(CType(r.order_time, Double)).AddMinutes(10) > Now Then

                                            result("order_id") = r.order_id

                                            Exit For

                                        Else

                                            r.order_status = 0

                                        End If
                                    End If
                                Next

                            End If
                        Else
                            result.Add("NoClient", "Herovo")
                        End If

                        context.SaveChanges()

                    End If

                    Return ConstructResponse(200, "OK", result)

                End Using

            Catch ex As Exception
                Return ConstructResponse(500, ex.InnerException.Message, Nothing)
            End Try

        End Function

        <FunctionState(FunctionState.FState.Stable), PostParametrData({"client_id", "order_from_address", "order_from_location", "order_to_address", "order_to_location", "order_comment", "order_time", "order_user_phone", "city_id"}, _
            {GetType(Guid), GetType(String), GetType(String), GetType(String), GetType(String), GetType(String), GetType(Integer), GetType(String), GetType(Guid)})>
        Public Function CreateOrder() As Dictionary(Of String, Object)

            Dim result As New Dictionary(Of String, Object)

            If (IsNothing(HttpContext.Current.Request("client_id")) = True) Then

                Return ConstructResponse(500, "NEED_PARAMETRS", Nothing)

            End If

            If (HttpContext.Current.Request("client_id") = "") Then

                Return ConstructResponse(500, "NEED_PARAMETRS", Nothing)

            End If

            If (IsNothing(HttpContext.Current.Request("order_from_address")) = True) Then

                Return ConstructResponse(500, "NEED_PARAMETRS", Nothing)

            End If

            If (HttpContext.Current.Request("order_from_address") = "") Then

                Return ConstructResponse(500, "NEED_PARAMETRS", Nothing)

            End If

            If (IsNothing(HttpContext.Current.Request("order_from_location")) = True) Then

                Return ConstructResponse(500, "NEED_PARAMETRS", Nothing)

            End If

            If (HttpContext.Current.Request("order_from_location") = "") Then

                Return ConstructResponse(500, "NEED_PARAMETRS", Nothing)

            End If

            If (IsNothing(HttpContext.Current.Request("order_to_address")) = True) Then

                Return ConstructResponse(500, "NEED_PARAMETRS", Nothing)

            End If

            If (HttpContext.Current.Request("order_to_address") = "") Then

                Return ConstructResponse(500, "NEED_PARAMETRS", Nothing)

            End If

            If (IsNothing(HttpContext.Current.Request("order_to_location")) = True) Then

                Return ConstructResponse(500, "NEED_PARAMETRS", Nothing)

            End If

            If (HttpContext.Current.Request("order_to_location") = "") Then

                Return ConstructResponse(500, "NEED_PARAMETRS", Nothing)

            End If

            If (IsNothing(HttpContext.Current.Request("order_time")) = True) Then

                Return ConstructResponse(500, "NEED_PARAMETRS", Nothing)

            End If

            If (HttpContext.Current.Request("order_time") = "") Then

                Return ConstructResponse(500, "NEED_PARAMETRS", Nothing)

            End If



            Dim ord As New orders

            Dim cid As Guid

            Try

                cid = Guid.Parse(HttpContext.Current.Request("client_id"))

                Dim request As HttpRequest = HttpContext.Current.Request

                Dim orderTime As Integer = CType(Val(HttpContext.Current.Request("order_time")), Integer)

                If orderTime <= 0 Then

                    Throw New Exception("BAD_ORDER_TIME_VALUE")

                End If

                Using context As New TaxiEntities()

                    Dim cidString As String = cid.ToString.ToUpper

                    Dim cln As clients = context.clients.FirstOrDefault(Function(x) x.client_udid = cidString)
                    If IsNothing(cln) = True Then

                        Return ConstructResponse(500, "UNKNOW_UDID", Nothing)

                    End If

                    Dim myOrders = context.orders.Where(
                        CType(Function(x) x.order_status = True And x.client_id = cln.client_id, Func(Of orders, Boolean))).AsEnumerable().Where(
                            CType(Function(x)
                                      Return CType((x.order_create.Value.AddMinutes(CType(x.order_time, Double)).AddMinutes(10) > Now And x.order_status = True And (x.torders.AsEnumerable.Count(Function(y) y.torder_status = 6) > 0)), Boolean)
                                  End Function, Func(Of orders, Boolean)))

                    If IsNothing(myOrders) = False Then
                        If myOrders.Count > 0 Then
                            Return ConstructResponse(500, "HER_TEBE", Nothing)
                        End If
                    End If

                    Dim myOrdersToClose = context.orders.Where(
                        CType(Function(x) x.order_status = True And x.client_id = cln.client_id, Func(Of orders, Boolean))).AsEnumerable().Where(
                            Function(x)
                                Return CType((x.order_create.Value.AddMinutes(CType(x.order_time, Double)).AddMinutes(10) > Now And x.order_status = True), Boolean)
                            End Function)


                    For Each mytc In myOrdersToClose
                        mytc.order_status = CType(0, Boolean?)
                    Next


                    ord.order_id = Guid.NewGuid
                    ord.client_id = cln.client_id
                    ord.order_create = Now

                    If (IsNothing(request("order_comment")) = False) Then If request("order_comment") <> "" Then ord.order_comment = request("order_comment")
                    If (IsNothing(request("order_user_phone")) = False) Then If request("order_user_phone") <> "" Then ord.order_comment = request("order_user_phone")

                    ord.order_from_address = request("order_from_address")
                    ord.order_from_location = request("order_from_location")
                    ord.order_status = 1
                    ord.order_time = orderTime
                    ord.order_to_address = request("order_to_address")
                    ord.order_to_location = request("order_to_location")

                    context.orders.Add(ord)
                    context.SaveChanges()
                    result.Add("order_id", ord.order_id.ToString)

                    Dim cityId As String = HttpContext.Current.Request("city_id")

                    result.Add("taxists", GetNearest(ord.order_id.ToString, cityId))
                End Using
            Catch ex As Exception

                Dim erro As String = String.Format("{0} ({1}).", ex.Message, ex.StackTrace)

                Dim tmp As Exception

                tmp = ex.InnerException

                While IsNothing(tmp) = False

                    erro += String.Format(" {0}({1})", tmp.Message, tmp.StackTrace)

                    tmp = tmp.InnerException

                End While

                Return ConstructResponse(500, erro, Nothing)


            End Try

            Return ConstructResponse(200, "OK", result)

        End Function

        <NeedAuth, PostParametrData({"coords"}, {GetType(String)}), Description("Taxi drivers must call this function every 30 seconds. This function update driver location")>
        Public Function ImHere() As Dictionary(Of String, Object)

            Dim result As New Dictionary(Of String, Object)

            Dim session As New WSession(HttpContext.Current)

            Try

                Dim tid As Guid = Guid.Parse(session.Data("taxi_id"))

                Using context As New TaxiEntities()

                    Dim coord As String = HttpContext.Current.Request("coords")

                    Dim off = context.taxist.Where(Function(x) x.taxi_isonline = True)

                    For Each t As taxist In off

                        If IsNothing(t.taxi_lastaction) = True Then Continue For

                        If t.taxi_lastaction.Value.AddSeconds(35) < Now Then

                            t.taxi_isonline = False

                        End If

                    Next

                    Dim tx As taxist = context.taxist.FirstOrDefault(Function(x) x.taxi_id = tid)

                    tx.taxi_lastaction = Now
                    tx.taxi_location = CType(IIf(IsNothing(coord) = True, "", coord), String)
                    tx.taxi_isonline = True

                    context.SaveChanges()

                    result.Add("result", "OK")
                End Using
            Catch ex As Exception

                Return ConstructResponse(500, ex.Message, Nothing)

            End Try

            Return ConstructResponse(200, "OK", result)

        End Function

        <FunctionState(FunctionState.FState.Stable), Description("Check status of requests in table taxi order. If number of not answerd and not missed timeout taxi drivers less than 3, then add new drivers."), PostParametrData({"order_id", "city_id"}, {GetType(Guid), GetType(Guid)})>
        Public Function ProcessingOrder() As Dictionary(Of String, Object)

            Dim result As New Dictionary(Of String, Object)

            Dim goi As Guid = Guid.Parse(HttpContext.Current.Request("order_id"))
            Dim cid As Guid = Guid.Parse(HttpContext.Current.Request("city_id"))

            Using _context As New TaxiEntities()

                Dim order As orders = _context.orders.FirstOrDefault(Function(x) x.order_id = goi)

                If IsNothing(order) = True Then
                    Return ConstructResponse(500, "ORDER_NOT_EXISTS", Nothing)
                End If

                If order.order_status = 1 Then
                    Return ConstructResponse(500, "ORDER_CLOSED", Nothing)
                End If

                Dim taxists = _context.torders.Where(Function(x) x.torder_status = 0 Or x.torder_status = 1 Or x.torder_status = 2 Or x.torder_status = 6)
                For Each t As torders In taxists
                    If t.torder_status = 0 Then
                        If t.torder_update.Value.AddSeconds(95) < Now Then
                            t.torder_status = 2
                        End If
                    Else
                        If t.torder_update.Value.AddSeconds(180) < Now Then
                            If t.torder_status <> 6 Then t.torder_status = 5
                        End If
                    End If
                Next

                _context.SaveChanges()

                Dim cnt As Integer = _context.torders.Count(Function(x) x.order_id = goi And (x.torder_status = 0 Or x.torder_status = 1))
                cnt = 6 - cnt


                If cnt > 0 Then
                    GetNearest(goi.ToString, cid.ToString, cnt) ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                End If

                Dim res As New ArrayList

                Dim tord = _context.torders.Where(Function(x) x.order_id = goi And (x.torder_status < 2 Or x.torder_status = 6)).AsEnumerable.ToList

                For Each t In tord

                    If t.orders.order_create.Value.AddMinutes(CType(t.orders.order_time, Double)).AddMinutes(10) < Now Then Continue For

                    Dim d As New Drivers
                    d.city_id = cid
                    If IsNothing(t.taxist.rating.FirstOrDefault) = False Then d.rating = CType(t.taxist.rating.Average(Function(x) x.rating_rate), Integer) Else d.rating = 0
                    d.taxi_carnumber = t.taxist.taxi_carnumber
                    d.taxi_color = t.taxist.taxi_color
                    d.taxi_id = t.taxist.taxi_id
                    d.taxi_lastname = t.taxist.taxi_lastname
                    d.taxi_location = t.taxist.taxi_location
                    d.taxi_marka = t.taxist.taxi_marka
                    d.taxi_model = t.taxist.taxi_model
                    d.taxi_photo = t.taxist.taxi_photo
                    If t.taxist.taxi_photo <> "" Then d.taxi_photo = String.Format("/Images/{0}", t.taxist.taxi_photo) Else d.taxi_photo = ""

                    d.taxt_firstname = t.taxist.taxt_firstname
                    d.price = t.torder_price

                    If t.taxist.rating.Count <> 0 Then d.taxi_rating = CType(t.taxist.rating.Average(Function(x) x.rating_rate), Integer) Else d.taxi_rating = 0

                    d.taxi_rating_count = t.taxist.rating.Count

                    res.Add(d)
                Next

                result.Add("drivers", res)

                Return ConstructResponse(200, "OK", result)
            End Using
        End Function

#Region "Other functions"
        <HideData>
        Public Function latlng2distance(lat1 As Decimal, long1 As Decimal, lat2 As Decimal, long2 As Decimal) As Decimal

            Const r As Integer = 6371000

            ' //перевод коордитат в радианы
            lat1 = CType((Math.PI / 180), Decimal)
            lat2 *= CType((Math.PI / 180), Decimal)
            long1 *= CType((Math.PI / 180), Decimal)
            long2 *= CType((Math.PI / 180), Decimal)

            ' //вычисление косинусов и синусов широт и разницы долгот
            Dim cl1 = Math.Cos(lat1)
            Dim cl2 = Math.Cos(lat2)
            Dim sl1 = Math.Sin(lat1)
            Dim sl2 = Math.Sin(lat2)
            Dim delta = long2 - long1
            Dim cdelta = Math.Cos(delta)
            Dim sdelta = Math.Sin(delta)

            '//вычисления длины большого круга
            Dim y = Math.Sqrt(Math.Pow(cl2 * sdelta, 2) + Math.Pow(cl1 * sl2 - sl1 * cl2 * cdelta, 2))
            Dim x = sl1 * sl2 + cl1 * cl2 * cdelta
            Dim ad = Math.Atan2(y, x)
            Dim dist As Decimal = CType((ad * r), Decimal) ' //расстояние между двумя координатами в метрах

            Return dist
        End Function
        <HideData>
        Public Function ToRadians(num As Double) As Double

            Return (Math.PI / 180) * num

        End Function
        <HideData>
        Public Function GetDistance(lat1 As Decimal, lat2 As Decimal, lng1 As Decimal, lng2 As Decimal) As Double


            Const R As Double = 6371 '// km

            Dim sLat1 As Double = Math.Sin(ToRadians(lat1))
            Dim sLat2 As Double = Math.Sin(ToRadians(lat2))
            Dim cLat1 As Double = Math.Cos(ToRadians(lat1))
            Dim cLat2 As Double = Math.Cos(ToRadians(lat2))
            Dim cLon As Double = Math.Cos(ToRadians(lng1) - ToRadians(lng2))

            Dim cosD As Double = sLat1 * sLat2 + cLat1 * cLat2 * cLon

            Dim d As Double = Math.Acos(cosD)

            Dim dist As Double = R * d

            Return dist


        End Function
        <HideData>
        Public Function smart_qiwi() As String

            Const result As String = ""

            If InStr(HttpContext.Current.Request.UserHostAddress, "92.46.53.228") = 0 Then Return ""

            Dim txtId As String = HttpContext.Current.Request("txn_id")
            Dim sum As String = CType(Val(HttpContext.Current.Request("sum")), String)
            Dim txnDate As String = HttpContext.Current.Request("txn_date")
            Dim account As String = String.Format("7{0}", HttpContext.Current.Request("account"))

            Dim command As String = HttpContext.Current.Request("command")
            Using context As New TaxiEntities()

                Select Case command

                    Case "check"

                        Dim txt As taxist = context.taxist.FirstOrDefault(Function(x) x.taxi_phone = account)

                        Dim code As String = Now.Hour & Now.Minute & Now.Second & Now.Millisecond & Now.Day & Now.Month & Now.Year

                        If IsNothing(txt) = False Then
                            HttpContext.Current.Response.Write(String.Format("<?xml version=""1.0"" encoding=""UTF-8""?><response><osmp_txn_id>{0}</osmp_txn_id><result>0</result><comment>READY_FOR_PAY</comment></response>", txtId))
                        Else
                            HttpContext.Current.Response.Write(String.Format("<?xml version=""1.0"" encoding=""UTF-8""?><response><osmp_txn_id>{0}</osmp_txn_id><result>5</result><comment>USER_NOT_FOUND</comment></response>", txtId))
                        End If


                    Case "pay"

                        'Dim _context As New TaxiEntities()

                        Dim oldtxt As transfers

                        oldtxt = context.transfers.FirstOrDefault(Function(x) x.txt_id = txtId)

                        If IsNothing(oldtxt) = False Then

                            HttpContext.Current.Response.Write(String.Format("<?xml version=""1.0"" encoding=""UTF-8""?><response><osmp_txn_id>{0}</osmp_txn_id><prv_txn>{1}</prv_txn><sum>{2}</sum><result>0</result><comment>OK</comment></response>", txtId, oldtxt.transfer_code, oldtxt.transfer_amount))

                        Else

                            Dim txt As taxist = context.taxist.FirstOrDefault(Function(x) x.taxi_phone = account)

                            Dim code As String = Now.Hour & Now.Minute & Now.Second & Now.Millisecond & Now.Day & Now.Month & Now.Year

                            If IsNothing(txt) = False Then

                                Dim tr As New transfers

                                tr.client_id = context.taxist.FirstOrDefault(Function(x) x.taxi_phone = account).taxi_id
                                tr.transfer_amount = CType(sum, Decimal?)
                                tr.transfer_code = code
                                tr.transfer_date = Now
                                tr.transfer_id = Guid.NewGuid
                                tr.transfer_sdate = txnDate
                                tr.txt_id = txtId

                                context.transfers.Add(tr)
                                context.SaveChanges()

                                HttpContext.Current.Response.Write(String.Format("<?xml version=""1.0"" encoding=""UTF-8""?><response><osmp_txn_id>{0}</osmp_txn_id><prv_txn>{1}</prv_txn><sum>{2}</sum><result>0</result><comment>OK</comment></response>", txtId, code, sum))
                            Else
                                HttpContext.Current.Response.Write(String.Format("<?xml version=""1.0"" encoding=""UTF-8""?><response><osmp_txn_id>{0}</osmp_txn_id><result>5</result><comment>USER_NOT_FOUND</comment></response>", txtId))

                            End If
                        End If

                End Select

                Return result
            End Using
        End Function
        Public Function TestDate() As String

            Return Now.ToString

        End Function
        <HideData>
        Public Function SendSms(phone As String, message As String) As String

            If phone.Length <> 11 Then Return "BAD_PHONE"
            If Mid(phone, 1, 1) <> "7" Then Return "BAD_FORMAT"

            Dim req As New WebClient
            Try

                req.Encoding = Encoding.UTF8

                Dim result As String = req.DownloadString(String.Format("http://smsc.kz/sys/send.php?login=Smartaxi.kz&psw=12345678&charset=utf-8&phones={0}&mes={1}", phone, message))

                If InStr(LCase(result), "error") <> 0 Then
                    Return result
                End If

            Catch ex As Exception

                Return ex.Message

            End Try

            Return "OK"

        End Function
#End Region

    End Module

End Namespace
